﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Core
{
    public class InitialiseActionPresenterInitialisationStage : PresenterInitialisationStage
    {
        public override bool Initialise(IPresenterInitialisationContext context)
        {
            context.ThrowIfNull("context");

            Delegate initAction = context.InitialisationAction;
            IPresenter current = context.Current;

            if (initAction != null && current != null)
            {
                //if the initialisation action is set then it should take an instance of the created presenter
                Type createdPresenterType = current.GetType();
                var methodParameters = initAction.Method.GetParameters();

                ExceptionHelper.ThrowIf<ArgumentException>(methodParameters.Length != 1, "Cannot invoke presenter initialisation action: Wrong number of parameters");
                ExceptionHelper.ThrowIf<ArgumentException>(!methodParameters[0].ParameterType.IsAssignableFrom(createdPresenterType), "Cannot invoke presenter initialisation action: Invalid parameter type");

                //invoke the initialisation action
                initAction.DynamicInvoke(current);
            }

            return true;
        }
    }
}
